var app = getApp(), fetchApi = require("../../../utils/httpPost.js")
import Dialog from '../../../component/vant/dialog/dialog';
import Toast from '../../../component/vant/toast/toast';
const message = '是否确认取消该订单？'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgurl: app.getImgUrl(),
    states1: [0, 1, 2],
    currentTab: 0,
    orderType: 0,
    orderstate:-1,
    pageSize:5,
    pageIndex: 1,
    scrollTop: 0,
    scrollHeight:0,
    hasData:false,
    orderList:[],
    loading: false,
    netWork: false,
    isLoading: true,
    visible:false,
    itemData:[],
    from_type:0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('productList options',options)
    var that = this;
    // that.data.currentTab = parseInt(options.index)
    // that.setData({
    //   currentTab: parseInt(options.index)
    // })
    // that.data.orderType = that.data.states1[that.data.currentTab];
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var isLogin = app.getStorageSync("isLogin");
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    }else{
      if(this.data.currentTab == 0){
        this.initOp();
      }
    }
  },
  initOp:function(){
    this.data.pageIndex = 1
    this.setData({
      currentTab: this.data.currentTab,
      loading: false,
      netWork: false,
      isLoading: true,
      hasData:false,
      orderList:[]
    })
    this.onHttpInit(this.data.orderType)
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function (orderType) {
    var that = this;
    fetchApi.httpPost('/device/water/order/list', {
      // state: state,
      order_type: orderType, //订单类型  0 - 水卡打水订单  1 - 扫码打水订单  2 - 水卡充值订单
      pageSize: that.data.pageSize,
      pageIndex: that.data.pageIndex
    }, function (res) {
      if (res.data.code == 0) {
        if (res.data.totalcount > 0) {
          that.data.pageIndex = that.data.pageIndex + 1
          console.log("订单列表数据", res)
          var orders = res.data.data.orderList;
          if(orders!=undefined && orders.length > 0){
            for (var index in orders) {
              that.data.orderList.splice(that.data.orderList.length, 0, orders[index]);
            }
            that.setData({
              hasData: true,
              orderList: that.data.orderList
            })
          }
        }
      }
      wx.stopPullDownRefresh() //停止下拉刷新
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  handleChange({ detail }) {
    console.log('handleChange',detail)
    var that = this
    this.data.pageIndex = 1
    that.setData({
      currentTab: detail.index,
      loading: false,
      netWork: false,
      isLoading: true,
      hasData:false,
      orderList:[]
    });
    that.data.orderstate = that.data.states1[detail.index]
    that.onHttpInit(that.data.orderstate)
  },
  goOrderDetail:function(t){
    console.log('goOrderDetail t',t)
    var state = t.currentTarget.dataset.state
    var orderid = t.currentTarget.dataset.orderid;
    var orderType = t.currentTarget.dataset.ordertype;
    console.log('orderType',orderType);
    // if(orderType == 6){
    //   wx.navigateTo({
    //     url: "/pagesPlatform/pages/food/submit/index?is_order=1&order_id=" + orderid,
    //   });
    // }else{
    // }
    wx.navigateTo({
      url: "/pages/order/detail/index?state=" + state + "&order_id=" + orderid
    });
  },
  //去评价
  goAppraise:function(e){
    console.log('goAppraise e',e)
    var orderid = e.currentTarget.dataset.orderid;
    var infoid = e.currentTarget.dataset.infoid;
    wx.navigateTo({
      url: '/pages/order/appraise/appraise?order_id=' + orderid + '&infoid=' + infoid,
    })
  },
  goPayOrderBalance(e){
    var orderId = e.currentTarget.dataset.orderid;
    console.log('goPayOrderBalance',e);
    wx.navigateTo({
      url: '/pages/order/payBalance/index?order_id=' + orderId,
    })
  },
  //扫码核销
  goVerifyQrCode(e){
    var orderId = e.currentTarget.dataset.orderid;
    var infoId = e.currentTarget.dataset.infoid;
    console.log('goVerifyQrCode',e);
    wx.navigateTo({
      url: '/pages/order/verify/index?order_id=' + orderId + '&info_id=' +infoId,
    })
  },
  goShareGroup(e){
    var item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '../groupShare/index?order_id=' + item.id,
    })
  },
  //去手动核销
  goVerifyOrder(e){
    console.log('goVerifyOrder e',e)
    var orderId = e.currentTarget.dataset.orderid;
    var that = this;
    var message = "是否发起核销该订单？"
    Dialog.confirm({
      title: '核销订单',
      message
    }).then(() => {
      that.onHttpVerifyOrderReg(orderId)
    })
    .catch(() => {
      Dialog.close();
    });
  },
  onHttpVerifyOrderReg: function (orderId){
    console.log('orderId',orderId)
    var that = this
    fetchApi.httpPost('/product/order/verifyOrderReg', {
      order_id: orderId,
    }, function (res) {
      console.log("核销申请订单 返回数据", res)
      if (res.data.code == 0) {
        Toast.success('核销申请成功');
        that.initOp()
      } else {
        Toast.fail(res.data.msg);
      }
    },function(){})
  },
  refundOrder(e){
    console.log('refundOrder e',e)
    var orderId = e.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: '/pages/order/refund/index?type=0&orderId=' + orderId,
    })
  },
  payMoney:function(t){
    console.log('payMoney',t);
    var order_id = t.currentTarget.dataset.orderid
    var user_coupon_id = t.currentTarget.dataset.usercouponid;
    var showcoupon = t.currentTarget.dataset.showcoupon;
    var isAppointment = t.currentTarget.dataset.isappointment;
    var isVisit = t.currentTarget.dataset.isVisit;
    var orderType = t.currentTarget.dataset.ordertype;
    if(showcoupon == 1){
      wx.navigateTo({
        url: '/pages/coupon/previewQrcode/index?qrcode_type=coupon&coupon_id=' + user_coupon_id+'&order_id='+order_id,
      })
    }else{
      if(orderType == 6){
        wx.navigateTo({
          url: "/pagesPlatform/pages/food/detail/index?is_order=1&order_id=" + order_id,
        });
      }else{
        wx.navigateTo({
          url: '/pages/pay/paySubmit/index?order_id=' + order_id 
          + '&isAppointment=' + isAppointment
        })
      }

      // this.payMoneyOp(order_id)
    }
  },
  payMoneyOp:function(order_id){
    var that = this
    fetchApi.httpPost('/pay/bingge/requestPay', {
      order_id: order_id,
      subject:'购买商品服务'
    }, function (res) {
      console.log('提交订单',res)
      if (res.data.code == 0) {
        var pay_data = res.data.data;
        var wxpayinfo = JSON.parse(res.data.data)
        console.log('pay_data',pay_data)
        if(wxpayinfo.result_code == 'SUCCESS'){
          wx.requestPayment({
            timeStamp: wxpayinfo.timeStamp,
            nonceStr: wxpayinfo.nonceStr,
            package: wxpayinfo.package,
            signType: wxpayinfo.signType,
            paySign: wxpayinfo.paySign,
            success (res) { 
              console.log('requestPayment success',res)
              wx.redirectTo({
                url: '/pages/pay/payResult/index?order_id=' + order_id,
              })
            },
            fail (res) {
              console.log('requestPayment fail',res)
             }
          })
        }
      } else {
        that.setData({ isLoading: false, loading: true, netWork: true })
      }
    }, function () {
        that.setData({  isLoading: false,  loading: true,  netWork: true, }) 
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.initOp()
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      isLoading: true
    })
    this.onHttpInit(this.data.orderstate)
  },
  cancelOrder:function(e){
    var order_id = e.currentTarget.dataset.orderid
    var that = this
    Dialog.confirm({
      title: '取消订单',
      message
    }).then(() => {
      that.onHttpCancelOrder(order_id)
    })
    .catch(() => {
      Dialog.close();
    });
  },
  onHttpCancelOrder: function (order_id){
    console.log('order_id',order_id)
    var that = this
    fetchApi.httpPost('/product/order/cancelOrder', {
      order_id: order_id,
    }, function (res) {
      console.log("取消订单 返回数据", res)
      if (res.data.code == 0) {
        Toast.success('取消成功');
        that.initOp()
      } else {
        Toast.fail(res.data.msg);
      }
    },function(){})
  },

})